package com.lancoo.klgcourseware.ui.widget;

import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.text.Layout;
import android.text.style.LineBackgroundSpan;
import android.text.style.LineHeightSpan;
import android.util.Log;
import android.widget.TextView;

/**
 * @author John
 */
public class FlexibleUnderLineSpan implements LineBackgroundSpan, LineHeightSpan {
    private Paint paint;
    private TextView textView;
    private float offsetY;
    private float spacingExtra;

    /**
     *
     * @param textView 所依赖的textView
     * @param color 颜色
     * @param thickness 厚度
     * @param dashPath 虚线长度
     * @param offsetY 与文本的间隔
     * @param spacingExtra 行距
     */
    public FlexibleUnderLineSpan(TextView textView, int color, float thickness, float dashPath,
                               float offsetY, float spacingExtra) {
        this.paint = new Paint();
        this.paint.setColor(color);
        this.paint.setStyle(Paint.Style.STROKE);
        this.paint.setPathEffect(new DashPathEffect(new float[] { dashPath, dashPath }, 0));
        this.paint.setStrokeWidth(thickness);
        this.textView = textView;
        this.offsetY = offsetY;
        this.spacingExtra = spacingExtra;
    }

    @Override
    public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v,
                             Paint.FontMetricsInt fm) {
//        fm.ascent -= spacingExtra;
//        fm.top -= spacingExtra;
        if (start == 0){
            fm.descent += spacingExtra;
            fm.bottom += spacingExtra;
        }
    }

    @Override
    public void drawBackground(Canvas canvas, Paint p, int left, int right, int top, int baseline,
                               int bottom, CharSequence text, int start, int end, int lnum) {
        int lineNum = textView.getLineCount();

        for (int i = 0; i < lineNum; i++) {
            Layout layout = textView.getLayout();
            Path path = new Path();
            path.moveTo(layout.getLineLeft(i), layout.getLineBottom(i) - spacingExtra + offsetY);
            path.lineTo(layout.getLineRight(i), layout.getLineBottom(i) - spacingExtra + offsetY);
            canvas.drawPath(path, this.paint);
        }
    }

    public void setColor(int color){
        this.paint.setColor(color);
    }
}
